package com.wyp168.leetcode.listnode;

/**
 * @ClassName AddTwoNumbers
 * @Description TODO
 * @Author wyp168
 * @Date 2022/6/27 09:36
 */
public class AddTwoNumbers {
    public static void main(String[] args) {
        ListNode a = new ListNode(9);
        ListNode b = new ListNode(9);
        ListNode c = new ListNode(9);
        ListNode d = new ListNode(9);
        ListNode e = new ListNode(9);
        ListNode f = new ListNode(9);
        ListNode g = new ListNode(9);
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;
        e.next = f;
        f.next = g;


        ListNode aa = new ListNode(9);
        ListNode bb = new ListNode(9);
        ListNode cc = new ListNode(9);
        ListNode dd = new ListNode(9);
        aa.next = bb;
        bb.next = cc;
        cc.next = dd;

//        ListNode a = new ListNode(2);
//        ListNode b = new ListNode(4);
//        ListNode c = new ListNode(3);
//        a.next = b;
//        b.next = c;
//
//        ListNode aa = new ListNode(5);
//        ListNode bb = new ListNode(6);
//        ListNode cc = new ListNode(4);
//        aa.next = bb;
//        bb.next = cc;




        System.out.println(addTwoNumbers(a, aa));

    }
    /**
     * @description: 该方法用于解决两个链表相加和
     * @author wyp168
     * @date: 2022/6/27 09:36
     */

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //是否进位，默认为0
        int isCarried = 0;
        ListNode res = new ListNode();
        ListNode next = res;

        while (l1 !=null && l2 != null) {
            next.val = l1.val + l2.val + isCarried;
            if (next.val >= 10) {
                next.val -= 10;
                isCarried = 1;
            } else {
                isCarried = 0;
            }
            l1 = l1.next;
            l2 = l2.next;
            if (l1 != null || l2 != null || isCarried == 1) {
                next.next = new ListNode();
                next = next.next;
            }
        }

        while (l1 != null) {
            next.val = l1.val + isCarried;
            if (next.val >= 10) {
                next.val -= 10;
                isCarried = 1;
            } else {
                isCarried = 0;
            }
            l1 = l1.next;
            if (l1 != null || isCarried == 1) {
                next.next = new ListNode();
                next = next.next;
            }
        }

        while (l2 != null) {
            next.val = l2.val + isCarried;
            if (next.val >= 10) {
                next.val -= 10;
                isCarried = 1;
            } else {
                isCarried = 0;
            }
            l2 = l2.next;
            if (l2 != null || isCarried == 1) {
                next.next = new ListNode();
                next = next.next;
            }
        }

        if (isCarried != 0) {
            next.val = 1;
        }
        return res;
    }
}
